// 改顺序
marketData.reverse()
const chartDataManager = {
    // 市场指标数据
    marketData: marketData,
    // 获取指定日期范围的数据
    getDateRangeData: function(days) {
        const startIndex = Math.max(0, this.marketData.length - days);
        const rangeData = this.marketData.slice(startIndex);

        return {
            dates: rangeData.map(item => item.date),
            szCount: rangeData.map(item => item.szCount),
            ztCount: rangeData.map(item => item.ztCount),
            dtCount: rangeData.map(item => item.dtCount),
            ztHeight: rangeData.map(item => item.ztHeight),
            lbCount: rangeData.map(item => item.lbCount),
            remarks: rangeData.map(item => ({
                date: item.date,
                sector: item.remark
            }))
        };
    },

    // 根据日期获取最强板块信息
    getRemarkByDate: function(date) {
        const dayData = this.marketData.find(item => item.date === date);
        return dayData ? {
            date: dayData.date,
            sector: dayData.remark
        } : null;
    }
};

// 初始化图表
let stockChart;
let currentDays = 30; // 默认显示近30天数据
let visibleSeries = ['szCount', 'ztCount', 'dtCount', 'ztHeight', 'lbCount'];

function initChart() {
    // 初始化ECharts实例
    stockChart = echarts.init(document.getElementById('stock-chart'));

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', function() {
        stockChart.resize();
    });

    // 初始加载数据
    updateChart(currentDays);
}

// 更新图表数据
function updateChart(days) {
    const data = chartDataManager.getDateRangeData(days);

    // 图表配置项
    const option = {
        // 全局禁用动画
        animation: false,
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            },
            formatter: function(params) {
                // 获取当前日期
                const date = params[0].name;

                // 获取最强板块信息
                const sectorInfo = chartDataManager.getRemarkByDate(date);

                // 构建自定义提示框内容
                let tooltipContent = `<div class="font-bold mb-1">${date}</div>`;

                // 添加各项指标数据
                params.forEach(param => {
                    let indicatorName = '';
                    switch(param.seriesName) {
                        case 'szCount':
                            indicatorName = '上涨数量';
                            break;
                        case 'ztCount':
                            indicatorName = '涨停数量';
                            break;
                        case 'dtCount':
                            indicatorName = '跌停数量';
                            break;
                        case 'ztHeight':
                            indicatorName = '连板高度';
                            break;
                        case 'lbCount':
                            indicatorName = '连板数量';
                            break;
                    }

                    const value = param.value;
                    const unit = param.seriesName === 'szCount' ? '' : '';

                    tooltipContent += `<div class="flex items-center mb-1">
                        <span class="inline-block w-3 h-3 mr-2" style="background-color: ${param.color}"></span>
                        <span>${indicatorName}: ${value}${unit}</span>
                    </div>`;
                });

                // 添加最强板块信息
                if (sectorInfo) {
                    tooltipContent += `<div class="mt-2 pt-2 border-t border-gray-200">
                        <div class="font-semibold">备注</div>
                        <div class="flex justify-between mt-1">
                            <span>${sectorInfo.sector}</span>
                        </div>
                    </div>`;
                }

                return tooltipContent;
            }
        },
        legend: {
            data: [
                { name: 'szCount', textStyle: { color: '#1a56db' } },
                { name: 'ztCount', textStyle: { color: '#10b981' } },
                { name: 'dtCount', textStyle: { color: '#ef4444' } },
                { name: 'ztHeight', textStyle: { color: '#f59e0b' } },
                { name: 'lbCount', textStyle: { color: '#3b82f6' } }
            ],
            formatter: function(name) {
                switch(name) {
                    case 'szCount':
                        return '上涨数量';
                    case 'ztCount':
                        return '涨停数量';
                    case 'dtCount':
                        return '跌停数量';
                    case 'ztHeight':
                        return '连板高度';
                    case 'lbCount':
                        return '连板数量';
                }
            },
            top: 0
        },
        grid: {
            left: '1%',
            right: '3%',
            bottom: '1%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: data.dates,
                axisPointer: {
                    type: 'shadow'
                },
                axisLabel: {
                    interval: Math.max(0, Math.floor(data.dates.length / 10)) // 控制X轴标签显示密度
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        type: 'dashed',
                        color: '#e5e7eb'
                    }
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '上涨数量',
                min: 0,
                axisLabel: {
                    formatter: '{value}',
                    color: '#1a56db'  // 使用与连板高度线条相同的颜色
                },
                nameTextStyle: {
                     color: '#1a56db'
                 },
                 axisLine: {
                     lineStyle: {
                         color: '#1a56db'
                     }
                 },
                splitLine: {
                    lineStyle: {
                        type: 'dashed'
                    }
                }
            },
             // 连板高度独立Y轴
             {
                 type: 'value',
                 name: '连板高度',
                 min: 0,
                 axisLabel: {
                     formatter: '{value}',
                     color: '#f59e0b'  // 使用与连板高度线条相同的颜色
                 },
                 nameTextStyle: {
                     color: '#f59e0b'
                 },
                 axisLine: {
                     lineStyle: {
                         color: '#f59e0b'
                     }
                 },
                 splitLine: {
                     show: false
                 },
                 position: 'right',
                 offset: 50  // 向右偏移60像素，与数量Y轴错开
             },
            {
                type: 'value',
                name: '数量',
                min: 0,
                axisLabel: {
                    formatter: '{value}'
                },
                splitLine: {
                    show: false
                },
                position: 'right'
            }
        ],
        series: [
            {
                name: 'szCount',
                type: 'line',
                smooth: false,
                data: data.szCount,
                symbol: 'circle',
                symbolSize: 6,
                yAxisIndex: 0,
                endLabel: {
                    show: true,
                    formatter: '上涨数量 {c}',
                    color: '#1a56db'
                },
                itemStyle: {
                    color: '#1a56db'
                },
                lineStyle: {
                    width: 3
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(26, 86, 219, 0.3)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(26, 86, 219, 0.1)'
                        }
                    ])
                }
            },
            {
                name: 'ztCount',
                type: 'line',
                smooth: false,
                data: data.ztCount,
                symbol: 'circle',
                symbolSize: 6,
                yAxisIndex: 2,
                endLabel: {
                    show: true,
                    formatter: '涨停数量 {c}',
                    color: '#10b981'
                },
                itemStyle: {
                    color: '#10b981'
                },
                lineStyle: {
                    width: 3
                }
            },
            {
                name: 'dtCount',
                type: 'line',
                smooth: false,
                data: data.dtCount,
                symbol: 'circle',
                symbolSize: 6,
                yAxisIndex: 2,
                endLabel: {
                    show: true,
                    formatter: '跌停数量 {c}',
                    color: '#ef4444'
                },
                itemStyle: {
                    color: '#ef4444'
                },
                lineStyle: {
                    width: 3
                }
            },
            {
                name: 'ztHeight',
                type: 'line',
                smooth: false,
                data: data.ztHeight,
                symbol: 'circle',
                symbolSize: 6,
                yAxisIndex: 1,
                endLabel: {
                    show: true,
                    formatter: '连板高度 {c}',
                    color: '#f59e0b'
                },
                itemStyle: {
                    color: '#f59e0b'
                },
                lineStyle: {
                    width: 3
                }
            },
            {
                name: 'lbCount',
                type: 'line',
                smooth: false,
                data: data.lbCount,
                symbol: 'circle',
                symbolSize: 6,
                yAxisIndex: 2,
                endLabel: {
                    show: true,
                    formatter: '连板数量 {c}',
                    color: '#3b82f6'
                },
                itemStyle: {
                    color: '#3b82f6'
                },
                lineStyle: {
                    width: 3
                }
            }
        ]
    };

    // 设置图表选项
    stockChart.setOption(option);

    // 更新可见系列
    updateVisibleSeries();
}

// 更新可见系列
function updateVisibleSeries() {
    const option = {
        series: ['szCount', 'ztCount', 'dtCount', 'ztHeight', 'lbCount'].map(seriesName => {
            return {
                name: seriesName,
                show: visibleSeries.includes(seriesName)
            };
        })
    };

    stockChart.setOption(option);
}

// 事件监听
document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表
    initChart();

    // 日期范围选择
    document.getElementById('date-range').addEventListener('change', function(e) {
        currentDays = parseInt(e.target.value);
        updateChart(currentDays);
    });

    // 指标筛选按钮
    document.getElementById('btn-all').addEventListener('click', function() {
        visibleSeries = ['szCount', 'ztCount', 'dtCount', 'ztHeight', 'lbCount'];
        updateVisibleSeries();
        updateButtonStyles('all');
    });

    document.getElementById('btn-rise').addEventListener('click', function() {
        visibleSeries = ['szCount', 'ztCount'];
        updateVisibleSeries();
        updateButtonStyles('rise');
    });

    document.getElementById('btn-fall').addEventListener('click', function() {
        visibleSeries = ['dtCount'];
        updateVisibleSeries();
        updateButtonStyles('fall');
    });

    document.getElementById('btn-continue').addEventListener('click', function() {
        visibleSeries = ['ztHeight', 'lbCount'];
        updateVisibleSeries();
        updateButtonStyles('continue');
    });
});

// 更新按钮样式
function updateButtonStyles(activeButton) {
    const buttons = ['all', 'rise', 'fall', 'continue'];

    buttons.forEach(btn => {
        const element = document.getElementById(`btn-${btn}`);
        if (btn === activeButton) {
            element.classList.remove('bg-gray-200', 'text-gray-700');
            element.classList.add('bg-primary', 'text-white');
        } else {
            element.classList.remove('bg-primary', 'text-white');
            element.classList.add('bg-gray-200', 'text-gray-700');
        }
    });
}
